<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Api\V1;

class GetOrderYf
{
    public $login = true; //是否需要登录才能访问该接口
    public $title = "通过购物车获取订单运费及积分优惠券";
    public $group = '订单';
    public $desc = "";

    public $input = [
        'cart_ids' => 'required;string;label=购物车id;comment=多个id使用英文逗号隔开;',
        'address_id' => 'int;label=地址id;',
    ];

    public $output = [
        'orderPrice' => [
            'pay_price' => 'label=商品金额',
            'total_price' => 'label=总金额',
            'pay_postage' => 'label=运费',
            'coupon_price' => 'label=优惠券抵扣金额',
            'deduction_price' => 'label=积分抵扣金额',
        ],
    ];

    public function run($param, $uid, $login_info)
    {
        $result = [];
        $address_info = (array)M('address')->where(['uid' => $uid, 'is_default' => 1])->find();
        $result['addressInfo'] = $address_info;
        $cart_info = [];
        $cart_list = M('shopcart')->where("id in({$param['cart_ids']}) AND uid={$uid}")->select();
        $user_info = M('user')->where(['uid' => $uid])->find();
        $pay_price = 0;
        $total_price = 0;
        $pay_postage = 0;
        $coupon_price = 0;
        $deduction_price = 0;
        foreach ($cart_list as $k => $v) {

            $v['spec_label'] = json_decode($v['spec_list'], true);
            $sku_name = array_column($v['spec_label'], 'sku_name');
            $sku_id_arr = array_column($v['spec_label'], 'sku_id');
            //获取库存
            $where['goods_id'] = $v['goods_id'];
            asort($sku_id_arr);
            if(count($sku_id_arr) == 1){
                $sku_id_arr[]= 0;
            }
            $where['sku_ids'] = join('-', $sku_id_arr);
            $data = M('goods_sku')->where($where)->find();
            $stock = $data['stock'] ? $data['stock'] : 0;

            if($login_info['vip_level'] == 0){
                $price = $data['sell_price'];
            }elseif($login_info['vip_level'] == 4){
                $price = $data['agent_price'];
            }else{
                $price = $data['vip_price'];
            }
            $vip_price = $data['vip_price'];

            $goods_info = M('goods')->where(['id' => $v['goods_id']])->find();
            $pay_price += $v['buy_num']*$price;

        }
        $total_price = $pay_price+$pay_postage-$coupon_price-$deduction_price;
        return [
            'orderPrice' => [
                'pay_price' => $pay_price,
                'total_price' => $total_price,
                'pay_postage' => $pay_postage,
                'coupon_price' => $coupon_price,
                'deduction_price' => $deduction_price,
            ]
        ];
    }
}
